package ca.utoronto.utm.csc301.euchre.common;

import java.util.HashMap;
import java.util.Map;

public class Card {
	private Suit suit;
	private Rank rank;
	
	private Card(Suit suit, Rank rank) {
		this.suit = suit;
		this.rank = rank;
	}
	
	private static Map<Integer, Card> cards = new HashMap<Integer, Card>();  
	
	public static synchronized Card getCard(Suit suit, Rank rank) {
		int id = generateId(suit, rank);
		
		Card card = cards.get(id);
		if (card == null) {
			card = new Card(suit, rank);
			cards.put(id, card);
		}
		
		return card;
	}
	
	/**
	 * Please note that this hash function was incorrect as given in the interface.
	 * @param suit
	 * @param rank
	 * @return
	 */
	private static int generateId(Suit suit, Rank rank) {
		return rank.ordinal() * 8 + suit.ordinal();
	}

	public void setSuit(Suit suit) {
		this.suit = suit;
	}

	public Suit getSuit() {
		return suit;
	}

	public void setRank(Rank rank) {
		this.rank = rank;
	}

	public Rank getRank() {
		return rank;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Card) {
			Card card = (Card) obj;
			return rank.equals(card.getRank()) && suit.equals(card.getSuit());
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		return generateId(suit, rank);
	}
}
